class MVVM {
    constructor(el, data) {
        this.el = document.querySelector(el);
        this._data = data;
        this.domPool = {};

        this.init();
    }

    init() {
        this.initData();
        this.initDom();
    }

    initDom() {
        this.bindDom(this.el);
        this.bindInput(this.el);
        console.log(this.domPool)
    }



    initData() {
        var _this = this;
        this.data = {};
        for (let key in this._data) {
            Object.defineProperty(this.data, key, {
                get() {
                    return _this._data[key];
                },
                set(newValue) {
                    _this._data[key] = newValue;
                    _this.domPool[key].innerHTML = newValue;
                }

            })
        }
        console.log(this.data)

        // ES6 Proxy
        // this.data = new Proxy(this.data , {
        //     get(target,key){
        //         return Reflect.get(target,key);
        //     },
        //     set(target,key,value){
        //         this.domPool[key] = value;
        //         return Reflect.set(target,key,value);
        //     }
        // })
    }

    bindDom(el) {
        const childNodes = el.childNodes;
        childNodes.forEach(item => {
            if (item.nodeType === 3) {
                const _value = item.nodeValue;
                if (_value.trim().length) {
                    let isValid = /\{\{(.+?)\}\}/.test(_value);
                    if (isValid) {
                        const _key = item.nodeValue.match(/\{\{(.+?)\}\}/)[1].trim();
                        this.domPool[_key] = item.parentNode;
                        item.parentNode.innerHTML = this.data[_key] || undefined
                    }
                }
            }

            item.childNodes && this.bindDom(item)
        })
    }

    bindInput(el) {
        const _allInput = el.querySelectorAll('input')
        _allInput.forEach(input => {
            const _vModel = input.getAttribute('v-model');
            if (_vModel) {
                input.addEventListener('keyup', this.handleInput.bind(this, _vModel, input), false)
            }
        });
    }

    handleInput(key, input) {
        const _value = input.value;
        this.data[key] = _value;
    }


}